package com.asialjim.wechat.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <h1><em>ASIAL JIM JAVA DOC</em></h1><hr/>
 * <h2>CLASS DESCRIPTION <i>[ NAME: JsonUtils ]</i></h2><strong>
 * <p> json util
 * </strong><p><p><em>Copyright &copy; Asial Jim Co., LTD</em><hr/>
 *
 * @author Asial Jim &nbsp;&nbsp; <span>Email:<a href="mailto:asialjim@hotmail.com">asialjim@hotmail.com</a> &nbsp;&nbsp; <a href="asialjim@qq.com">asialjim@qq.com</a></span>
 * @version 1.0.0
 * @since 2021/1/26   &nbsp;&nbsp; JDK 8
 */
@Slf4j
public class JsonUtils {
    /**
     * ObjectMapper
     */
    private static ObjectMapper mapper = new ObjectMapper();

    static {
        // 转成对象时，可以忽略多余参数
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        //mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        //mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public static String toJson(Object value) {
        if (value == null){return "{}";}
        try {
            return mapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            log.error("Json cast failed!{}", e.getMessage());
            return null;
        }

    }

    public static <T> T toObject(String json, JavaType javaType) {
        try {
            return mapper.readValue(json, javaType);
        } catch (Exception e) {
            log.error("Json cast failed!{}",e.getMessage());
            return null;
        }
    }

    public static <T> T toObject(Map<String,Object> source, Class<T> valueType){
        return toObject(toJson(source),valueType);
    }

    public static <T> T toObject(String json, Class<T> valueType) {
        try {
            return mapper.readValue(json, valueType);
        } catch (Exception e) {
            log.error("Json cast failed!{}", e.getMessage());
            return null;
        }
    }

    /**
     * 将JSON字符串转换为对象
     * @param json JSON字符串
     * @param typeReference 对象类型
     * @return 对象
     */
    public static <T> T toObject(String json, TypeReference<T> typeReference) {
        try {
            return mapper.readValue(json, typeReference);
        } catch (Exception e) {
            log.error("Json cast failed!{}", e.getMessage());
            return null;
        }
    }

    /**
     * 将JSON字符串转换为List对象
     * @param json JSON字符串
     * @param clazz 对象类型
     * @return 对象List
     */
    public static <T> List<T> toObjectList(String json, Class<T> clazz) {
        try {
            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, clazz);
            List<T> list = mapper.readValue(json, javaType);
            return list;
        } catch (Exception e) {
            try {
                return mapper.readValue(json, new TypeReference<List<T>>() {
                });
            } catch (IOException e1) {
                log.error("Json cast failed!{}", e.getMessage());
                return null;
            }
        }
    }

    public static <T> List<T> jsonToList(String json, Class<T> valueType) {
        List<T> list = null;
        try {
            @SuppressWarnings("deprecation")
            JsonParser parser = mapper.getJsonFactory().createJsonParser(json);
            JsonNode nodes = parser.readValueAsTree();
            list = new ArrayList<T>(nodes.size());
            for (JsonNode node : nodes) {
                list.add(mapper.readValue(node.textValue(), valueType));
            }
        } catch (Exception e) {
            log.error("Json cast failed!{}", e.getMessage());
            return null;
        }
        return list;

    }

    @SuppressWarnings("unchecked")
    public static <T> Map<String, T> jsonToMap(String json) {
        Map<String, T> userData = null;
        try {
            if (StringUtils.isNotBlank(json)) {
                userData = mapper.readValue(json, Map.class);
            } else {
                userData = new HashMap<>();
            }
            return userData;
        } catch (Exception e) {
            log.error("Json cast failed!{}", e.getMessage());
            return null;
        }
    }

    public static Map<String,Object> objectToMap(Object obj){
        return jsonToMap(toJson(obj));
    }
}